<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">仓库管理</div>
          <div class="card-tools">
            <el-button type="primary" @click="handleAdd">新增仓库</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入仓库名称"
          prefix-icon="Search"
          @keydown.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" class="search-button">搜索</el-button>
            <el-button @click="handleReset" class="reset-button">清空</el-button>
          </template>
        </el-input>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="repositoryList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="序号" width="80" type="index" align="center">
          <template #default="scope">
            {{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="仓库名称" min-width="180" align="center" />
        <el-table-column label="仓库归属" min-width="150" align="center">
          <template #default="scope">
            {{ scope.row.cname || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="person" label="联系人" min-width="120" align="center" />
        <el-table-column prop="phone" label="联系电话" min-width="150" align="center" />
        <el-table-column prop="email" label="邮箱" min-width="180" align="center" />
        <el-table-column prop="address" label="地址" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)" size="small">修改</el-button>
            <el-button 
              type="text" 
              @click="handleStatusChange(scope.row)" 
              size="small" 
              :style="scope.row.status === 1 ? 'color: #f56c6c' : 'color: #67c23a'"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" @click="handleDelete(scope.row)" size="small" danger>删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination mt-4 flex justify-end items-center">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑仓库' : '新增仓库'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库归属" prop="cellId">
          <el-select v-model="formData.cellId" placeholder="请选择仓库归属" :loading="communitiesLoading" filterable>
            <el-option v-for="community in communityList" :key="community.id" :label="community.name" :value="community.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="person">
          <el-input v-model="formData.person" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注信息" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <div class="text-center py-4">是否确认删除该仓库？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete" :loading="deleteLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import type { RepositoryItem, RepositoryListParams, RepositoryPayload, RepositoryBackendItem } from '@/api/repository';
import { getRepositoryList, createRepository, updateRepository, deleteRepository, getRepositoryById, updateRepositoryStatus } from '@/api/repository';
import type { CommunityItem } from '@/api/community';
import { getCommunityList } from '@/api/community';

// 定义分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 定义搜索表单
const searchForm = reactive({
  keyword: ''
});

// 定义仓库列表数据
const repositoryList = ref<RepositoryItem[]>([]);
const loading = ref(false);

// 定义对话框相关数据
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentEditId = ref<number | null>(null);
const submitLoading = ref(false);

// 定义删除对话框相关数据
const deleteDialogVisible = ref(false);
const currentDeleteId = ref<number | null>(null);
const deleteLoading = ref(false);

// 定义表单数据和规则
const formRef = ref<FormInstance>();
const formData = reactive<Partial<{ id: number; name: string; cellId?: number; status: number; person: string; phone: string; email: string; address: string; remark?: string }>>({  
  name: '',
  cellId: undefined,
  status: 1,
  person: '',
  phone: '',
  email: '',
  address: '',
  remark: ''
});

// 小区列表数据
const communityList = ref<CommunityItem[]>([]);
const communitiesLoading = ref(false);

// 获取小区列表
const fetchCommunityList = async () => {
  try {
    communitiesLoading.value = true;
    const res = await getCommunityList();
    if (res.code === 0 && res.data) {
      communityList.value = res.data;
    } else {
      ElMessage.error(res.message || '获取小区列表失败');
    }
  } catch (error) {
    ElMessage.error('获取小区列表失败');
  } finally {
    communitiesLoading.value = false;
  }
};

// 组件挂载时获取小区列表
onMounted(() => {
  fetchCommunityList();
});

const formRules: FormRules = {
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  cellId: [{ required: true, message: '请选择仓库归属', trigger: 'blur' }],
  person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
};



// 将后端数据转换为前端模型
const transformBackendData = (backendItems: RepositoryBackendItem[]): RepositoryItem[] => {
  return backendItems.map(item => ({
    id: item.id,
    name: item.name,
    cellId: item.cellId,
    cname: item.cname,
    status: item.status,
    person: item.person,
    phone: item.phone,
    email: item.email,
    address: item.address,
    remark: item.remark
  }));
};

// 获取仓库列表
const fetchRepositoryList = async () => {
  try {
    loading.value = true;
    // 构建查询参数
    const params: RepositoryListParams = {
      page: pagination.page,
      limit: pagination.limit,
      ...(searchForm.keyword && { name: searchForm.keyword })
    };
    
    // 调用API获取仓库列表
    const res = await getRepositoryList(params);
    
    if (res.code === 0 && res.data && res.data.list) {
      // 将后端返回的数据转换为前端使用的格式
      repositoryList.value = transformBackendData(res.data.list);
      // 由于API没有返回总条数，这里可以根据实际情况处理
      // 如果需要实现分页，可能需要修改API接口
    } else {
      ElMessage.error(res.message || '获取仓库列表失败');
    }
  } catch (error) {
    ElMessage.error('获取仓库列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchRepositoryList();
};

// 重置搜索
const handleReset = () => {
  searchForm.keyword = '';
  pagination.page = 1;
  fetchRepositoryList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchRepositoryList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchRepositoryList();
};

// 新增仓库
const handleAdd = () => {
  isEdit.value = false;
  currentEditId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑仓库
const handleEdit = async (row: RepositoryItem) => {
  isEdit.value = true;
  currentEditId.value = row.id;
  
  try {
    // 获取仓库详情
    const res = await getRepositoryById(row.id);
    if (res.code === 0 && res.data) {
      // 填充表单数据
      Object.assign(formData, res.data);
      dialogVisible.value = true;
    } else {
      ElMessage.error(res.message || '获取仓库详情失败');
    }
  } catch (error) {
    ElMessage.error('获取仓库详情失败');
  }
};

// 修改仓库状态
const handleStatusChange = async (row: RepositoryItem) => {
  try {
    // 调用API修改仓库状态
    const res = await updateRepositoryStatus(row.id);
    
    if (res.code === 0) {
      ElMessage.success('状态修改成功');
      // 刷新列表
      fetchRepositoryList();
    } else {
      ElMessage.error(res.message || '状态修改失败');
    }
  } catch (error) {
    ElMessage.error('状态修改失败');
  }
};

// 删除仓库
const handleDelete = (row: RepositoryItem) => {
  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentDeleteId.value) return;
  try {
    deleteLoading.value = true;
    // 调用API删除仓库
    const res = await deleteRepository(currentDeleteId.value);
    
    if (res.code === 0) {
      ElMessage.success('删除成功');
      deleteDialogVisible.value = false;
      fetchRepositoryList(); // 重新获取列表
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败');
  } finally {
    deleteLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    name: '',
    cellId: undefined,
    status: 1,
    person: '',
    phone: '',
    email: '',
    address: '',
    remark: ''
  });
  formRef.value?.clearValidate();
};

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    // 构建请求数据
    const payload: RepositoryPayload = {
      name: formData.name || '',
      cellId: formData.cellId,
      status: formData.status || 1,
      person: formData.person || '',
      phone: formData.phone || '',
      email: formData.email || '',
      address: formData.address || '',
      remark: formData.remark || ''
    };
    
    let res;
    if (isEdit.value && currentEditId.value) {
      // 编辑仓库
      res = await updateRepository({ ...payload, id: currentEditId.value });
    } else {
      // 新增仓库
      res = await createRepository(payload);
    }
    
    if (res.code === 0) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      fetchRepositoryList(); // 重新获取列表
    } else {
      ElMessage.error(res.message || (isEdit.value ? '编辑失败' : '新增失败'));
    }
  } catch (error) {
    // 表单验证失败时会进入这里
    if (error === false) return;
    ElMessage.error(isEdit.value ? '编辑失败' : '新增失败');
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载时获取数据
fetchRepositoryList();
</script>

<style scoped>
.main {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

.card-tools {
  display: flex;
  gap: 10px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.search-area .el-input {
  min-width: 300px;
  flex: 1;
}

.search-area .el-input .el-input-group__append {
  padding: 0;
  background-color: #fff;
  display: flex;
  align-items: center;
}

.search-button {
  margin-right: 5px;
}

.reset-button {
  margin-left: 0;
}

.search-area .el-button {
  white-space: nowrap;
  height: 100%;
}

.pagination {
  margin-top: 10px;
}
</style>